﻿//  -------------------- iSharePoint -------------------- //
// 
//  Company:	IT Complex, LLC
//  Project:	Smart.Common
//  File name:	ChoiceValueCollection.cs
//  Developer:	Solomatov Igor
//  Created:	15.04.2012
// 
//  -------------------- iSharePoint -------------------- //

using System;
using System.Collections.Generic;
using System.Linq;

namespace Smart.Common.Entities
{
	public class ChoiceValueCollection : List<string>
	{
		public ChoiceValueCollection()
		{
		}

		public ChoiceValueCollection(IEnumerable<string> collection)
			: base(collection)
		{
			RemoveEmpty();
		}

		public ChoiceValueCollection(int capacity)
			: base(capacity)
		{
		}

		protected void RemoveEmpty()
		{
			RemoveAll(string.IsNullOrEmpty);
		}

		public override string ToString()
		{
			return
				this.CastToString(SPH.MultiLookupValueDelimiter);
		}

		/// <summary>
		/// Checks whether collection is empty
		/// </summary>
		public bool IsEmpty
		{
			get { return Count <= 0; }
		}

		/// <summary>
		/// Ensure specified values exists
		/// </summary>
		/// <returns>true, if value changed</returns>
		public bool Ensure(params string[] values)
		{
			var oldCount = Count;

			AddRange(values.Where(value => !value.IsNullOrEmpty() && !Exists(value.EqIC)));

			return oldCount < Count;
		}

		/// <summary>
		/// Set values
		/// </summary>
		public void Set(params string[] values)
		{
			Clear();

			AddRange(values.Where(value => !value.IsNullOrEmpty()));
		}

		/// <summary>
		/// Compare arrays by it's children items values 
		/// </summary>
		public virtual bool Equals(IEnumerable<string> obj)
		{
			if (obj == null)
				return false;

			var hs = new HashSet<string>(this, StringComparer.OrdinalIgnoreCase);

			return
				hs.SetEquals(obj);
		}

		/// <summary>
		/// Calculate children items hash code
		/// </summary>
		public virtual int GetChildrenHashCode()
		{
			return
				this.Aggregate(0,
							   (code, value) =>
							   code ^ StringComparer.OrdinalIgnoreCase.GetHashCode(value));
		}
	}
}